<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理系统</title>
    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .section {
            margin-bottom: 40px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .error {
            color: red;
            margin: 10px 0;
        }
        .success {
            color: green;
            margin: 10px 0;
        }
        button {
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
        }
        .nav {
            margin-bottom: 20px;
        }
        .nav a {
            margin-right: 10px;
            text-decoration: none;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="nav">
            <a href="index.html">用户管理</a>
            <a href="role.html">角色管理</a>
            <a href="menu.html">菜单管理</a>
        </div>
        
        <div id="errorMessage" class="error"></div>
        <div id="successMessage" class="success"></div>
        
        <div class="section">
            <h2>添加角色</h2>
            <form id="roleForm">
                <div class="form-group">
                    <label for="roleName">角色名称：</label>
                    <input type="text" id="roleName" required>
                </div>
                <div class="form-group">
                    <label for="roleDescription">角色描述：</label>
                    <input type="text" id="roleDescription" required>
                </div>
                <button type="submit">添加角色</button>
            </form>
        </div>

        <div class="section" id="editRoleSection" style="display: none;">
            <h2>编辑角色</h2>
            <form id="editRoleForm">
                <input type="hidden" id="editRoleId">
                <div class="form-group">
                    <label for="editRoleName">角色名称：</label>
                    <input type="text" id="editRoleName" required>
                </div>
                <div class="form-group">
                    <label for="editRoleDescription">角色描述：</label>
                    <input type="text" id="editRoleDescription" required>
                </div>
                <button type="submit">更新角色</button>
                <button type="button" id="cancelEditButton">取消</button>
            </form>
        </div>

        <div class="section">
            <h3>角色列表</h3>
            <table id="roleTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>角色名称</th>
                        <th>描述</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <script>
        const API_URL = 'http://localhost:3000';
        const errorMessageElement = document.getElementById('errorMessage');
        const successMessageElement = document.getElementById('successMessage');

        function showMessage(message, isError = false) {
            const element = isError ? errorMessageElement : successMessageElement;
            element.textContent = message;
            setTimeout(() => {
                element.textContent = '';
            }, 3000);
        }

        // 获取所有角色
        async function fetchRoles() {
            try {
                const response = await fetch(`${API_URL}/roles`);
                if (!response.ok) {
                    throw new Error('获取角色列表失败');
                }
                const roles = await response.json();
                
                const tbody = document.querySelector('#roleTable tbody');
                tbody.innerHTML = '';
                roles.forEach(role => {
                    tbody.innerHTML += `
                        <tr>
                            <td>${role.id}</td>
                            <td>${role.name}</td>
                            <td>${role.description}</td>
                            <td>
                                <button onclick="editRole(${role.id})">编辑</button>
                                <button onclick="deleteRole(${role.id})">删除</button>
                            </td>
                        </tr>
                    `;
                });
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 添加角色
        document.getElementById('roleForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const roleData = {
                    name: document.getElementById('roleName').value,
                    description: document.getElementById('roleDescription').value
                };

                const response = await fetch(`${API_URL}/roles`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(roleData)
                });

                if (!response.ok) {
                    throw new Error('添加角色失败');
                }

                document.getElementById('roleForm').reset();
                showMessage('角色添加成功！');
                fetchRoles();
            } catch (error) {
                showMessage(error.message, true);
            }
        });

        // 编辑角色
        async function editRole(id) {
            try {
                const response = await fetch(`${API_URL}/roles/${id}`);
                if (!response.ok) {
                    throw new Error('获取角色信息失败');
                }
                const role = await response.json();
                
                // 填充编辑表单
                document.getElementById('editRoleId').value = role.id;
                document.getElementById('editRoleName').value = role.name;
                document.getElementById('editRoleDescription').value = role.description;

                // 显示编辑表单
                document.getElementById('editRoleSection').style.display = 'block';
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 更新角色
        document.getElementById('editRoleForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const id = document.getElementById('editRoleId').value;
            const updatedRoleData = {
                name: document.getElementById('editRoleName').value,
                description: document.getElementById('editRoleDescription').value
            };

            try {
                const response = await fetch(`${API_URL}/roles/${id}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(updatedRoleData)
                });

                if (!response.ok) {
                    throw new Error('更新角色失败');
                }

                showMessage('角色更新成功！');
                fetchRoles();
                document.getElementById('editRoleSection').style.display = 'none';
            } catch (error) {
                showMessage(error.message, true);
            }
        });

        // 取消编辑
        document.getElementById('cancelEditButton').addEventListener('click', () => {
            document.getElementById('editRoleSection').style.display = 'none';
        });

        // 删除角色
        async function deleteRole(id) {
            if (confirm('确定要删除这个角色吗？')) {
                try {
                    const response = await fetch(`${API_URL}/roles/${id}`, {
                        method: 'DELETE'
                    });

                    if (!response.ok) {
                        throw new Error('删除角色失败');
                    }

                    showMessage('角色删除成功！');
                    fetchRoles();
                } catch (error) {
                    showMessage(error.message, true);
                }
            }
        }

        // 初始化
        fetchRoles();
    </script>
</body>
</html> 